var supplierId = window.localStorage.getItem('userId')
var imgList = [];
// 加载选择商品类别
//获取一级类别
$.ajax({
    type:'get',
    url:webUrl + '/goodsType/findAll',
    dataType:'json',
    success:function (data) {
        let dataJson = data.content;
        // 一级导航加载
        for (let i=0;i<dataJson.length;i++){
            let option = `<option class="fM" value='` +dataJson[i].goodsTypeId + `'>`+dataJson[i].goodsTypeName+`</option>`;
            $('.fL').append(option)
        }
        checkSL()
    }
})

//选择一级类别加载二级类别
function checkSL(){
    console.log($('.fL').val())
    $('.sL').html('')
    let goodsId = $('.fL').val();
    $.ajax({
        type:'get',
        url:webUrl + '/goodsTypeTwo/findByGoodsTypeId',
        data:{
            goodsTypeId:goodsId
        },
        dataType:'json',
        success:function (data) {
            let secendDataJson = data.content;

            console.log(secendDataJson)
            if(secendDataJson.length>0){
                for (let i=0;i<secendDataJson.length;i++) {
                    secendOptions = `<option value='`+secendDataJson[i].goodsTypeTwoId+`'>` + secendDataJson[i].goodsTypeTwoName + `</option>`
                    $('.sL').append(secendOptions)
                }
                checkTL()
            }else{
                let obj =  `<option>暂无数据</option>`
                $('.sL').append(obj)
                $('.tL').html('')
                $('.tL').append(obj)
                return false
            }

        }
    })
}
// 选择二级类别加载三级类别
function checkTL() {
    let goodsId = $('.sL').val();
    $.ajax({
        type:'get',
        url:webUrl + '/goodsTypeThree/findByGoodsTypeTwoId',
        data:{
            goodsTypeTwoId:goodsId
        },
        dataType:'json',
        success:function(data){
            $('.tL').html('')
            if(data.content.length>0){
                for(let i=0;i<data.content.length;i++){
                    let obj =  `<option  value='`+data.content[i].goodsTypeThreeId+`'>`+data.content[i].goodsTypeThreeName+`</option>`
                    $('.tL').append(obj)
                }
            }else{
                let obj =  `<option disabled>暂无数据</option>`
                $('.tL').append(obj)
            }

        }
    })
}
// 默认点击获取本地图库
function clickFile(){
    $('#imgFile').click()
}
// 获取图片数据库
function getImages(){
    $("#imgBoxOptions").html('')
    $.ajax({
        url:webUrl + '/supplier/getimages/'+supplierId,
        success:function (res) {
            for(i in res.content){
                let imgOption = `<div class="imgOption"><img src="`+res.content[i].imagesUrl+`"></div>`
                $("#imgBoxOptions").append(imgOption)
            }
        }
    })
}

getImages()
// 上传图片
function imgPreview(fileDom){
    //判断是否支持FileReader
    if (window.FileReader) {
        var reader = new FileReader();
    } else {
        alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
    }

    //获取文件
    let file = fileDom.files[0];
    let imageType = /^image\//;
    //是否是图片
    if (!imageType.test(file.type)) {
        alert("请选择图片！");
        return;
    }

    //读取完成
    //获取图片dom
    reader.onload = function(e) {
        // 添加图片信息 预览


    };
    let data = new FormData();
    data.append('multipartFile', file);
    data.append('SupplieruserId', supplierId);
    $.ajax({
        url:webUrl+'/supplier/loadimg',
        type:'POST',
        data: data,
        contentType: false,
        processData: false,
        success:function (args) {
            getImages()
        }
    })
    reader.readAsDataURL(file);
}
$(document).on('click','.imgOption',function () {
    let index = $.inArray($(this).children().attr('src'),imgList)
    if(index<0){
        //只能选择一张照片
        if(imgList.length>0){
            alert('只能选择一张照片！')
            return false;
        }
        $(this).addClass('active')
        imgList.push($(this).children().attr('src'))
    }else{
        $(this).removeClass('active')
        imgList.splice(index,1)
    }

})

// 上传商品信息
$('.setBtn').click(function(){

    let goodsTypeId = $('.tL').val();
    let commodityName = $('#commodityName').val();
    let brandName = $('#brandName').val();//牌号商标
    let specificationModel = $('#specificationModel').val();//规格型号
    let manufacturer = $('#manufacturer').val();//生产厂家
    let measurementUnit = $('#measurementUnit').val();//计量单位
    let price = $('#price').val();//价格
    let concessionalRate = $('#concessionalRate').val();//优惠价
    let membershipPrice = $('#membershipPrice').val();//会员价
    let proportion = $('#proportion').val();//比重
    let appearance = $('#appearance').val();//外观
    let productBrief = $('#productBrief').val();//产品简介
    let productIntroduction = $('#productIntroduction').val();//产品介绍
    // let productPicture = $('#productPicture').val();//产品图片
    let inventorySituation = $('#inventorySituation').val();//库存

    if(goodsTypeId == '暂无数据'){
        alert("请选择有效的商品类型！");
        return false
    }
    $.ajax({
        type:'post',
        url:webUrl+'/goods/add',
        data:{
            map:1,
            supplierId:supplierId,
            goodsTpye:goodsTypeId,
            commodityName:commodityName,
            brandName:brandName,
            specificationModel:specificationModel,
            manufacturer:manufacturer,
            measurementUnit:measurementUnit,
            price:price,
            concessionalRate:concessionalRate,
            membershipPrice:membershipPrice,
            proportion:proportion,
            appearance:appearance,
            productBrief:productBrief,
            productIntroduction:productIntroduction,
            productPicture:imgList[0],
            inventorySituation:inventorySituation
        },
        success:function(data){
            console.log(data)
            if(data.code == 1){
               $.confirm({
                    title: '确认',
                    content: '上传成功！',
                    type: 'green',
                    icon: 'glyphicon glyphicon-question-sign',
                    buttons: {
                        ok: {
                            text: '查看已发布的商品',
                            btnClass: 'btn-primary',
                            action: function() {
                                location.href = "Published.html"; //指向下载资源（此处为目标文件的输出数据流）
                            }
                        },
                        cancel: {
                            text: '继续上传',
                            btnClass: 'btn-primary',
                            action: function() {
                                window.location.reload(); //刷新页面
                            }
                        }
                    }
                })
            }
        }
    })
})
// 展示选中的图片
function showImg() {
    $("#showimg").html('')
    for(i in imgList){
        let imgOption = `<div class="imgOption"><img src="`+imgList[i]+`"></div>`
        $("#showimg").append(imgOption)
    }
}
